# -*- coding: utf-8 -*-
from django.shortcuts import render,render_to_response
from django.http import HttpResponse
from cmdb.models import Ticket, Server
from .forms import StatementForm, GetsnForm
from django.db.models import Count, Sum
import datetime
import MySQLdb,os,re
import jinja2

#####饼状图分析#####
#def home(request):
#    mysql_ip='192.168.1.7'
#    mysql_user='root'
#    mysql_password='123456'
#    mysql_DB='cmdb'
#    #################
#    conn= MySQLdb.connect(mysql_ip,mysql_user,mysql_password,mysql_DB)
#    cursor = conn.cursor()
#    sql_getcount = "select  cabinet_list,count(sn)  from cmdb_server group by cabinet_list;"
#    cursor.execute(sql_getcount)
#    data = cursor.fetchall()
#    list = []
#nds.conf    for i in data:
#        dic={'value':int(i[1]), 'name':i[0]}
#        list.append(dic.copy())
#
#    conn.close()
#    return render(request,'index.html',{'list': list})

####工单服务器数量统计#####
def ajax(request):
    if request.method == 'POST':
        print request.POST
        return HttpResponse('ok')
    else:
        return render_to_response('ajax.html')
def Get_sn(request):
    if request.method == 'POST':
#        global getsn
        # form 包含提交的数据
        form = GetsnForm(request.POST)
        # 如果提交的数据合法
        if form.is_valid():
#            ticket = form.cleaned_data['ticket']
            ipa = form.cleaned_data['ipa'].split('\r\n')
            for i in ipa:
                print i
            sn = 'haha'
##            ipa = str(ipa)
##            cmd = "wget https://%s  2>&1 | grep ILO | awk -F 'ILO' '{print $2}' |awk -F '’' '{print $1}'"  % ipa
##            sn = os.popen(cmd)
##            sn = sn.read()
#    mysql_ip='192.168.4.50'
#    mysql_user='root'
#    mysql_password='123456'
#    mysql_DB='cmdb'
#    #################
#    conn= MySQLdb.connect(mysql_ip,mysql_user,mysql_password,mysql_DB)
#    cursor = conn.cursor()
#    conn.close()
            return render(request,'get_sn_outprint.html',{'sn': sn})
 
    else:
        form = GetsnForm()

    return render(request, 'get_sn.html', {'form': form})

def List_all(request):
    server_list = ['A']
    list_A = []
    list_B = []
    list_C = []
    list_D = []
    list_E = []
    list_F = []
    All_server = Server.objects.filter(check=1)
#    All_server = Server.objects.filter(machine_type='physical')
    for server in All_server:
        if server.cabinet_list == 'A':
            list_A.append(server) 
        elif server.cabinet_list == 'B':
            list_B.append(server) 
        elif server.cabinet_list == 'C':
            list_C.append(server) 
        elif server.cabinet_list == 'D':
            list_D.append(server) 
        elif server.cabinet_list == 'E':
            list_E.append(server) 
        elif server.cabinet_list == 'F':
            list_F.append(server) 


    res = render(request, 'sn.html', {'list_res': list_A})
    fo = open("/home/Django/M2-commands.conf/M2-A-HP-HOSTS.conf", "w")
    fo.write( str(res) )
    fo.close()
    fin = open("/home/Django/M2-commands.conf/M2-A-HP-HOSTS.conf")
    a = fin.readlines()
    fout = open('/home/Django/M2-commands.conf/M2-A-HP-HOSTS.conf','w')
    b = ''.join(a[2:])
    fout.write(b)
    fin.close()
    fout.close()
    

    res = render(request, 'sn.html', {'list_res': list_B})
    fo = open("/home/Django/M2-commands.conf/M2-B-HP-HOSTS.conf", "w")
    fo.write( str(res) )
    fo.close()
    fin = open("/home/Django/M2-commands.conf/M2-B-HP-HOSTS.conf")
    a = fin.readlines()
    fout = open('/home/Django/M2-commands.conf/M2-B-HP-HOSTS.conf','w')
    b = ''.join(a[2:])
    fout.write(b)
    fin.close()
    fout.close()
 

    res = render(request, 'sn.html', {'list_res': list_C})
    fo = open("/home/Django/M2-commands.conf/M2-C-HP-HOSTS.conf", "w")
    fo.write( str(res) )
    fo.close()
    fin = open("/home/Django/M2-commands.conf/M2-C-HP-HOSTS.conf")
    a = fin.readlines()
    fout = open('/home/Django/M2-commands.conf/M2-C-HP-HOSTS.conf','w')
    b = ''.join(a[2:])
    fout.write(b)
    fin.close()
    fout.close()
 

    res = render(request, 'sn.html', {'list_res': list_D})
    fo = open("/home/Django/M2-commands.conf/M2-D-HP-HOSTS.conf", "w")
    fo.write( str(res) )
    fo.close()
    fin = open("/home/Django/M2-commands.conf/M2-D-HP-HOSTS.conf")
    a = fin.readlines()
    fout = open('/home/Django/M2-commands.conf/M2-D-HP-HOSTS.conf','w')
    b = ''.join(a[2:])
    fout.write(b)
    fin.close()
    fout.close()
 

    res = render(request, 'sn.html', {'list_res': list_E})
    fo = open("/home/Django/M2-commands.conf/M2-E-HP-HOSTS.conf", "w")
    fo.write( str(res) )
    fo.close()
    fin = open("/home/Django/M2-commands.conf/M2-E-HP-HOSTS.conf")
    a = fin.readlines()
    fout = open('/home/Django/M2-commands.conf/M2-E-HP-HOSTS.conf','w')
    b = ''.join(a[2:])
    fout.write(b)
    fin.close()
    fout.close()
 

    res = render(request, 'sn.html', {'list_res': list_F})
    fo = open("/home/Django/M2-commands.conf/M2-F-HP-HOSTS.conf", "w")
    fo.write( str(res) )
    fo.close()
    fin = open("/home/Django/M2-commands.conf/M2-F-HP-HOSTS.conf")
    a = fin.readlines()
    fout = open('/home/Django/M2-commands.conf/M2-F-HP-HOSTS.conf','w')
    b = ''.join(a[2:])
    fout.write(b)
    fin.close()
    fout.close()
 
#####传配置#####
    os.system('scp /home/Django/M2-commands.conf/*.conf root@192.168.4.24:/etc/icinga2/M2.d')
    os.system("ssh root@192.168.4.24 'systemctl restart icinga2'")


    return render(request, 'sn.html', {'list_res': list_C})
    
#    res = render(request, 'sn.html', {'sn_list': sn_list})
#    fo = open("/home/Django/M2-commands.conf/M2-C-HP-HOSTS.conf", "w+")
#    print res
#    fo.write( str(res) )
#    fo.close()
    
#    return render(request, 'sn.html', {'sn': sn_list})




#####报表统计#####
def statement(request):
    # 当提交表单时
    if request.method == 'POST':
        # form 包含提交的数据
        form = StatementForm(request.POST)
        # 如果提交的数据合法
        if form.is_valid():
#            ticket = form.cleaned_data['ticket']
            start_time = form.cleaned_data['start_time']
            end_time = form.cleaned_data['end_time']
            all_tickets = Ticket.objects.filter(end_time__range=[start_time, end_time])
            ticket_list = list(all_tickets.values('ticket_type').annotate(total=Count('ticket_type')))
            server_sum = list(all_tickets.values('ticket_type').annotate(total=Sum('server_number')))
#####手动取数据#####
#            mysql_ip='127.0.0.1'
#            mysql_user='root'
#            mysql_password='123456'
#            mysql_DB='cmdb'
#            conn= MySQLdb.connect(mysql_ip,mysql_user,mysql_password,mysql_DB)
#            cursor = conn.cursor()
#            sql_getcount = "select ticket_type,sum(server_number) from cmdb_ticket  group by ticket_type;"
#            cursor.execute(sql_getcount)
#            server_sum = cursor.fetchall()
#            server_sum = list(server_sum)
#            print server_sum
#            print ticket_list
#
#####################
            return render(request,'index.html',{'ticket_list':ticket_list ,'server_sum':server_sum})
#            return HttpResponse(ticket,count)
#            return HttpResponse(str(str(name)+' '+str(url)))
#            return HttpResponse(ipa)

    else:
        form = StatementForm()

    return render(request, 'statement.html', {'form': form})

#####专线探测####
#def map(request):
#    ip2='10.214.255.2'
#    ip62='10.214.255.62'
#    ip10='10.214.255.10'
#    ip50='10.214.255.50'
#    delay2 = 100
#    delay62 = 100
#    delay10 = 100
#    delay50 = 100
#    res=os.popen('ping -c1 -w1'+' '+ip2).read()
#    pattern_get_delay = re.compile('time=(\d+)\..+')
#    delay2 = re.findall(pattern_get_delay,res)
#    if delay2:
#        delay2 = delay2
#    else:
#        delay2 = 100
#    delay2 = int(delay2[0])
#    res=os.popen('ping -c1 -w1'+' '+ip62).read()
#    pattern_get_delay = re.compile('time=(\d+)\..+')
#    delay62 = re.findall(pattern_get_delay,res)
#    if delay62:
#        delay62 = delay62
#    else:
#        delay62 = 100
#    delay62 = int(delay62[0])
#    res=os.popen('ping -c1 -w1'+' '+ip10).read()
#    pattern_get_delay = re.compile('time=(\d+)\..+')
#    delay10 = re.findall(pattern_get_delay,res)
#    if delay10:
#        delay10 = delay10
#    else:
#        delay10 = 100
#    delay10 = int(delay10[0])
#    res=os.popen('ping -c1 -w1'+' '+ip50).read()
#    pattern_get_delay = re.compile('time=(\d+)\..+')
#    delay50 = re.findall(pattern_get_delay,res)
#    if delay50:
#        delay50 = delay50
#    else:
#        delay50 = [101]
#    delay50 = int(delay50[0])
#    return render(request,'map.html',{'delay2': delay2,'delay62': delay62,'delay10': delay10,'delay50': delay50})
